package servlets;

import Listeners.MyAsyncListener;
import Listeners.MyReadListener;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by hadoop on 17-6-15.
 * 异步处理
 */
@WebServlet(name = "AsyncServlet",urlPatterns = {"/async"},asyncSupported = true)
public class AsyncServlet extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<p>进入Servlet的时间: "+new Date()+"</p>");
        AsyncContext asyncContext = req.startAsync();
        //添加监听器
        asyncContext.addListener(new MyAsyncListener());
        asyncContext.setTimeout(60*1000);
        ServletInputStream inputStream = req.getInputStream();
        inputStream.setReadListener(new MyReadListener(inputStream,asyncContext));
//        asyncContext.start(new GetBookTarget(asyncContext));
        out.println("<p>结束Servlet的时间: "+new Date()+"</p>");
        out.flush();
    }
}

class GetBookTarget implements Runnable{
    private AsyncContext asyncContext;

    public GetBookTarget(AsyncContext asyncContext) {
        this.asyncContext = asyncContext;
    }

    @Override
    public void run() {
        try{
            Thread.sleep(2*1000);
            ServletRequest request = asyncContext.getRequest();
            List<String> list = new ArrayList<>();
            list.add("Java");
            list.add("Scala");
            list.add("Python");
            request.setAttribute("books",list);
            asyncContext.dispatch("/async.jsp");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
